<template>
  <div class="lab-list-component" @scroll="handleScroll">
    <!-- 实验室列表 -->
    <ul class="lab-items">
      <li 
        v-for="lab in store.labs" 
        :key="lab.id"
        :class="{ 'selected': selectedLabId === lab.id }"
        @click="selectLab(lab)"
      >
        <div class="lab-item">
          <span class="lab-name">{{ lab.name }}</span>
          <div class="lab-actions" v-if="(isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole) && selectedLabId === lab.id">
            <button class="download-btn" @click.stop="downloadLab(lab)" title="下载库存数据">
              <i class="fa fa-download"></i>
            </button>
            <button class="edit-btn" @click.stop="editLab(lab)" title="编辑">
              <i class="fa fa-edit"></i>
            </button>
            <button class="add-user-btn" @click.stop="addUserToLab(lab)" title="新增人员" v-if="!isEditRole">
              <i class="fa fa-user-plus"></i>
            </button>
            <button class="delete-btn" @click.stop="deleteLab(lab)" title="删除">
              <i class="fa fa-trash"></i>
            </button>
          </div>
        </div>
      </li>
    </ul>
    
    <!-- 加载状态 -->
    <div v-if="store.loadingMore" class="loading-more">
      加载中...
    </div>

    <!-- 无更多数据提示 -->
    <div v-if="!store.hasMore && store.labs.length > 0" class="no-more">
      没有更多实验室了
    </div>
    
    <!-- 空状态提示 -->
    <div v-if="store.labs.length === 0 && isAdmin" class="empty-state">
      暂无实验室，请点击上方"+"按钮创建
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, computed, ref } from 'vue';
import { useLabStore, type Lab } from '../../stores/labStore';
import type { User } from '../../types';

const emit = defineEmits<{
  (e: 'select', lab: Lab): void;
  (e: 'edit', lab: Lab): void;
  (e: 'delete', lab: Lab): void;
  (e: 'add-user', lab: Lab): void;
  (e: 'download', lab: Lab): void;
}>();

// 使用lab store
const store = useLabStore();

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 4
  );
});
const isEditRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 10
  );
});
const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 12
  );
});

// 计算属性：当前选中的实验室ID
const selectedLabId = computed(() => store.selectedLab?.id || null);

// 组件挂载时加载实验室列表
onMounted(async () => {
  await store.fetchLabs();
});

// 选择实验室
const selectLab = (lab: Lab) => {
  emit('select', lab);
};

// 编辑实验室
const editLab = (lab: Lab) => {
  emit('edit', lab);
};

// 删除实验室
const deleteLab = (lab: Lab) => {
  emit('delete', lab);
};

// 添加用户到实验室
const addUserToLab = (lab: Lab) => {
  emit('add-user', lab);
};

// 下载实验室库存数据
const downloadLab = (lab: Lab) => {
  emit('download', lab);
};

// 节流函数
const throttle = <T extends (...args: any[]) => any>(
  func: T,
  delay: number
): ((...args: Parameters<T>) => void) => {
  let lastCall = 0;
  return (...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func(...args);
    }
  };
};

// 处理滚动加载
const handleScroll = throttle((event: Event) => {
  const target = event.target as HTMLElement;
  const { scrollTop, scrollHeight, clientHeight } = target;
  
  // 当滚动到距离底部50px时触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 50 && !store.loadingMore && store.hasMore) {
    store.loadMoreLabs();
  }
}, 200); // 200ms的节流时间
</script>

<style scoped>
.lab-list-component {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
}

.lab-items {
  list-style: none;
  padding: 0;
  margin: 0;
}

.lab-items li {
  padding: 10px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.lab-items li:hover {
  background-color: #f0f0f0;
}

.lab-items li.selected {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.lab-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.lab-name {
  font-size: 14px;
  color: #333;
}

.lab-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.lab-items li.selected .lab-actions {
  opacity: 1;
}

.edit-btn, .delete-btn, .add-user-btn, .download-btn {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.edit-btn {
  background-color: #f0f0f0;
  color: #1890ff;
}

.edit-btn:hover {
  background-color: #e6f7ff;
}

.add-user-btn {
  background-color: #f0f0f0;
  color: #52c41a;
}

.add-user-btn:hover {
  background-color: #f6ffed;
}

.delete-btn {
  background-color: #f0f0f0;
  color: #ff4d4f;
}

.download-btn {
  background-color: #f0f0f0;
  color: #722ed1;
}

.download-btn:hover {
  background-color: #f9f0ff;
}

.delete-btn:hover {
  background-color: #fff1f0;
}

.empty-state {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 加载状态样式 */
.loading-more {
  padding: 12px;
  text-align: center;
  color: #666;
  font-size: 14px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin: 8px;
}

/* 无更多数据提示样式 */
.no-more {
  padding: 12px;
  text-align: center;
  color: #999;
  font-size: 14px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin: 8px;
}

/* 滚动条样式 */
.lab-list-component::-webkit-scrollbar {
  width: 6px;
}

.lab-list-component::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.lab-list-component::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.lab-list-component::-webkit-scrollbar-thumb:hover {
  background: #999;
}
</style>